#define _DEFAULT_SOURCE
#include "clog.h"
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>

void* worker_thread(void* arg) {
    int thread_id = *(int*)arg;
    
    for (int i = 0; i < 20; i++) {
        LOGI("Thread %d: processing task %d", thread_id, i + 1);
        
        if (i % 5 == 0) {
            LOGD("Thread %d: detailed processing info for task %d", thread_id, i + 1);
        }
        
        if (i % 8 == 0 && i > 0) {
            LOGW("Thread %d: resource contention detected at task %d", thread_id, i + 1);
        }
        
        if (i == 15) {
            LOGE("Thread %d: encountered error at task %d", thread_id, i + 1);
        }
        
        usleep(50000); // 休眠50ms
    }
    
    LOGI("Thread %d completed all tasks", thread_id);
    return NULL;
}

int main() {
    printf("Test App 2 starting...\n");
    
    LOGI("Multi-threaded application started");
    LOGD("Creating worker threads...");
    
    // 创建多个工作线程
    pthread_t threads[3];
    int thread_ids[3] = {1, 2, 3};
    
    for (int i = 0; i < 3; i++) {
        if (pthread_create(&threads[i], NULL, worker_thread, &thread_ids[i]) != 0) {
            LOGE("Failed to create thread %d", i + 1);
            return 1;
        }
        LOGD("Thread %d created successfully", i + 1);
    }
    
    // 主线程也生成一些日志
    for (int i = 0; i < 30; i++) {
        LOGI("Main thread: monitoring system status %d", i + 1);
        
        if (i % 15 == 0 && i > 0) {
            LOGW("Main thread: system load is increasing");
        }
        
        usleep(80000); // 休眠80ms
    }
    
    // 等待所有线程完成
    for (int i = 0; i < 3; i++) {
        pthread_join(threads[i], NULL);
        LOGD("Thread %d joined", i + 1);
    }
    
    LOGI("All threads completed successfully");
    LOGI("Multi-threaded application finished");
    
    printf("Test App 2 finished.\n");
    return 0;
}
